import Cesium, { Cartesian3 } from '../Ces/Cesium'

class EarthPin {
  _id: string
  _position: Cartesian3
  _pinGraphy
  _content: string
  pinCollection
  _onwer
  _dirty: boolean = false
  _createdGraphy: boolean = false
  _visible: boolean = true
  constructor(options) {
    let id = options.id

    if (!Cesium.defined(id)) {
      id = Cesium.createGuid()
    }
    this._id = id
    this._position = new Cesium.Cartesian3()
    if (Cesium.defined(options.position)) {
      Cesium.Cartesian3.clone(options.position, this._position)
    }
    this._pinGraphy = options.graphy
    this._content = options.content?? ''
    // set in owner
    this.pinCollection = undefined
  }

  get id() {
    return this._id
  }
  get owner() {
    return this._onwer
  }
  set owner(value) {
    this._onwer = value
  }
  get pinGraphy() {
    return this._pinGraphy
  }
  set pinGraphy(value) {
    this._pinGraphy = value
  }
  get content() {
    return this._content
  }
  set content(value) {
    if (value !== this._content) {
      this._dirty = true
      this._content = value
    }
  }
  get position() {
    return this._position
  }
  set position(value) {
    Cesium.Cartesian3.clone(value, this._position)
  }
  get visible() {
    return this._visible
  }
  set visible(value) {
    if (value !== this._visible) {
      this._visible = value
    }
    if (this.pinGraphy && this.pinGraphy.visible !== value) {
      this.pinGraphy.visible = value
    }
  }

  checkVisibility() {
    const owner = this._onwer
    if (Cesium.defined(owner) &&
      Cesium.defined(owner.isDestroyed) &&
      owner.isDestroyed()) {
      this._onwer = undefined
      return false
    }

    return true
  }

  update(viewer) {
    const pinGraphy = this._pinGraphy
    if (!Cesium.defined(pinGraphy)) {
      return
    }

    if (this._visible) {
      this.visible = this.checkVisibility()
    }

    if (!this._visible) {
      pinGraphy.visible = false
      return
    }

    if (!this._createdGraphy) {
      this._createdGraphy = true
      pinGraphy.createGraph(viewer.container, this)
      pinGraphy.visible = true
    }

    if (this._dirty) {
      this._dirty = false
      pinGraphy.content = this.content
    }

    // Cesium Version. this line remove in 2025
    const screenPosition =
      Cesium.SceneTransforms.wgs84ToWindowCoordinates ?
        Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene, this._position) :
        Cesium.SceneTransforms.worldToWindowCoordinates(viewer.scene, this._position)

    if (screenPosition) {
      screenPosition.x += viewer.container.offsetLeft
      screenPosition.y += viewer.container.offsetTop
      pinGraphy.showAt(screenPosition)
    }
  }

  destroy() {
    this._pinGraphy = this._pinGraphy && this._pinGraphy.destroy()
    this.pinCollection.remove(this)
    return Cesium.destroyObject(this)
  }

  isDestroyed() {
    return false
  }
}

export default EarthPin
